package cn.lxycx.dataterrace.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Jdbc {
	private static String username;
	private static String password;
	private static String url;
	private static String driver;
	private static Properties pros;
	private static Connection conn;
	static {
		try {
			pros = new Properties();
			pros.load(Jdbc.class.getResourceAsStream("/config"));//new FileInputStream(new File("config.properties")
			username = pros.getProperty("user");
			password = pros.getProperty("password");
			url = pros.getProperty("jdbcUrl");
			driver = pros.getProperty("driver");
			Class.forName(driver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取连接对象
	 * @throws SQLException 
	 * */
	public static Connection getConn() throws SQLException{
		//Context c = new InitialContext();
		//DataSource ds = c;
		if(conn==null||conn.isClosed()){
			 conn = DriverManager.getConnection(url, username, password);
		}
		return conn;
	}
	
	/**
	 * 获取连接对象
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 * */
	public static Connection getConn(String url, String username, String password,String driver) throws SQLException, ClassNotFoundException{
		Class.forName(driver);
		return DriverManager.getConnection(url, username, password);
	}
	
	
	
	/**
	 * 关闭链接
	 * @param conn
	 * 创建时间：2017年9月30日
	 *
	 */
	public static void closeConn(Connection conn){
		try {
			conn.close();
		} catch (SQLException e) {
			//closeConn(conn);
		}
	}
	
}
